// https://www.bilibili.com/video/BV11E411o7Fb?p=5
#include <bits/stdc++.h>
using namespace std;

// Global/class scope variables
vector<vector<char>> matrix=
{{' ',' ',' ','#',' ',' ',' '},
 {' ','#',' ',' ',' ','#',' '},
 {' ','#',' ',' ',' ',' ',' '},
 {' ',' ','#','#',' ',' ',' '},
 {'#',' ','#','E',' ','#',' '}}; //Input character matrix of size R x C

char block = '#';
char end_point = 'E';

int sr = 0; int sc = 0; // start grid
queue<int> rq,cq;

// Variables used to track the number of steps taken
int move_count = 0;
int nodes_left_in_layer = 1;
int nodes_in_next_layer = 0;

// Variables used to track whether the 'E' character
// ever gets reached during the BFS
bool reached_end = false;

// R x C matrix of false values used to track whether
// the node at position (i,j) has been visited
vector<vector<bool>> visited(matrix.size(),vector<bool>(matrix[0].size()));

int dr[4] = {-1, +1, 0, 0};
int dc[4] = {0, 0, -1, +1};


void explore_neighbours(int r, int c){
    for(int i = 0; i < 4;i++){
        int rr = r + dr[i];
        int cc = c + dc[i];

        // Skip out of bounds locations
        if(rr < 0 || cc < 0) continue;
        if(rr >=matrix.size() || cc >= matrix[0].size()) continue;

        // Skip visited locations or blocked cells
        if(visited[rr][cc]) continue;
        if(matrix[rr][cc]==block) continue;

        rq.push(rr);
        cq.push(cc);
        visited[rr][cc] = true;
        nodes_in_next_layer++;
    }
}

int solve(){
    rq.push(sr);
    cq.push(sc);
    visited[sr][sc] = true;

    while(!rq.empty()){
        int r = rq.front();
        int c = cq.front();
        rq.pop();
        cq.pop();

        if(matrix[r][c]==end_point){
            reached_end = true;
            break;
        }

        explore_neighbours(r,c);
        nodes_left_in_layer--;
        if(nodes_left_in_layer==0){
            nodes_left_in_layer = nodes_in_next_layer;
            nodes_in_next_layer = 0;
            move_count++;
        }
    }
    if(reached_end){
        return move_count;
    }
    return -1;
}



int main(){
    cout<< solve()<< endl;
    return 0;
}